package com.shekhar.paas.service;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.googlecode.charts4j.BarChart;
import com.googlecode.charts4j.BarChartPlot;
import com.googlecode.charts4j.Color;
import com.googlecode.charts4j.Data;
import com.googlecode.charts4j.Fills;
import com.googlecode.charts4j.GCharts;
import com.googlecode.charts4j.Plots;
import com.shekhar.paas.search.PaasProvider;
import com.shekhar.paas.vo.PaasCountInfo;

@Service(value = "googleChartService")
public class GoogleChartService implements ChartService {

    @Override
    public String generateChart(Set<PaasCountInfo> data, String title) {
        data = normalize(data);
        List<BarChartPlot> bars = new ArrayList<BarChartPlot>();
        for (PaasCountInfo paasCountInfo : data) {
            PaasProvider paasProvider = paasCountInfo.getPaasProvider();
            long normalizedCount = paasCountInfo.getNormalizedCount();
            BarChartPlot bar = Plots.newBarChartPlot(Data.newData(normalizedCount), paasProvider.getColor(), paasProvider.getDisplayName());
            bar.addTextMarker(paasCountInfo.getCount() + " tweets", Color.GOLD, 15, 0);
            bars.add(bar);
        }
        BarChart chart = GCharts.newBarChart(bars);
        chart.setSize(500, 400);
        chart.setBarWidth(BarChart.AUTO_RESIZE);
        chart.setTitle(title, Color.GREEN, 15);
        chart.setBackgroundFill(Fills.newSolidFill(Color.LIGHTGREY));
        chart.setAreaFill(Fills.newSolidFill(Color.LIGHTSEAGREEN));
        return chart.toURLString();
    }

    private Set<PaasCountInfo> normalize(Set<PaasCountInfo> data) {
        long max = 0L;
        for (PaasCountInfo paasCountInfo : data) {
            long count = paasCountInfo.getCount();
            if (count > max) {
                max = count;
            }
        }
        if (max <= 0) {
            return data;
        }
        Set<PaasCountInfo> copy = new LinkedHashSet<PaasCountInfo>();
        for (PaasCountInfo paasCountInfo : data) {
            long count = paasCountInfo.getCount();
            double normalizedCount = ((double) count / max) * 100;

            paasCountInfo = new PaasCountInfo(paasCountInfo, Double.valueOf(normalizedCount).longValue());
            copy.add(paasCountInfo);
        }
        return copy;
    }
}
